﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Diagnostics;
using StarfleetCommanderDomain;
using System.Data.EntityClient;

namespace StarfleetCommanderSecure.EF4
{
    public partial class SfeEntities
    {
        static bool _csIsInitialized;

        public string ToTraceString<T>(IQueryable<T> query)
        {
            var objectQuery = (System.Data.Objects.ObjectQuery) query;
            return objectQuery.ToTraceString();
        }
        public static SfeEntities Create()
        {
            if (_csIsInitialized == false)
                FindEfConnectionString();
            return new SfeEntities(SqlConnectionStringManager.EfConnectionString);
        }
        public static string ConnectionString{private get; set;}
        public static string GetDefaultEfConnectionString( )
        {
            var sCs = new System.Data.SqlClient.SqlConnectionStringBuilder(ConnectionString);

            var cs = new EntityConnectionStringBuilder
            {
                ProviderConnectionString = sCs.ToString(),
                Metadata = "res://*/EF4.Sfe.csdl|res://*/EF4.Sfe.ssdl|res://*/EF4.Sfe.msl",
                Provider = "System.Data.SqlClient"
            };
            return cs.ConnectionString;
        }

        private static void FindEfConnectionString()
        {
            _csIsInitialized = true;
            if (SqlConnectionStringManager.EfConnectionString.IsNullOrEmpty() == false)
                return;
            IEnumerable<string> strings = new[] { GetDefaultEfConnectionString() };

            strings = strings.Union(ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>().Select(x => x.ToString()));

           

                Action<SfeEntities> testConnectionPermission = dc => dc.Permissions.ToList();
            var lockObject = new object();
            int count=0;
            var messages = new List<string>();
                foreach (var cs in strings)
                {
                    count++;
                    if (cs.IsNullOrEmpty())
                        continue;
                        string efCs;
                        if (cs.Contains("metadata=") == false)
                        {
                            var scsb =
                                new System.Data.SqlClient.SqlConnectionStringBuilder(cs);
                            var ecsb = new EntityConnectionStringBuilder
                                           {
                                               ProviderConnectionString = scsb.ToString(),
                                               Metadata = "res://*/EF4.Sfe.csdl|res://*/EF4.Sfe.ssdl|res://*/EF4.Sfe.msl",
                                               Provider = "System.Data.SqlClient"
                                           };

                            efCs = ecsb.ConnectionString;

                        }
                        else
                        {
                            efCs = cs;

                        }
                        using (var dc = new SfeEntities(efCs))
                        {
                          
                        try
                        {
                            testConnectionPermission(dc);
                              var ecsb = new EntityConnectionStringBuilder(dc.Connection.ConnectionString);
                            
                            lock (lockObject)
                            SqlConnectionStringManager.SetConnectionString(ecsb.ProviderConnectionString,
                                                                           dc.Connection.ConnectionString);
                            return;
                        }
                        catch (System.Data.SqlClient.SqlException sqlEx)
                        {
                            messages.Add(sqlEx.Message);
                            Trace.WriteLine("Connection failed:" + sqlEx);
                        }
                        catch (System.Data.EntityException eEx)
                        {
                            messages.Add(eEx.Message);
                            Trace.WriteLine("Connection failed:" + eEx);
                        }
                    }
                }
                if (SqlConnectionStringManager.EfConnectionString.IsNullOrEmpty())
                    throw new ConfigurationErrorsException("No ef connection string found, tried " +count+":"+messages.Aggregate((s1,s2)=>s1+","+s2)+" - "+
                                                     ConfigurationManager.ConnectionStrings.Cast
                                                         <ConnectionStringSettings>().Select(x => x.Name).Aggregate(
                                                             (s1, s2) => s1 + "," + s2));
        }




      
    }


    public partial class IndexFragmentation :  IIndexFragmentation{}

    public partial class EspionageBuilding : IEspionageBuilding
    {}

    public partial class Position : IPosition
    {
       
        IGameSystem IPosition.GameSystem
        {
            get { return this.GameSystem; }
        }

    }
    public partial class Espionage :  IEspionage
    {

      
        StarfleetCommanderDomain.IEspionageBuilding IEspionage.EspionageBuilding
        {
            get {return  EspionageBuilding; }
        }

        
    }
    public partial class GameSystem : IGameSystem
    {
      

        short IGameSystem.GameSystem
        {
            get { return GameSystem1; }
            set { GameSystem1 = value; }
        }

       

    }
        public partial class EspionageReport :  IEspionageReport
        {
            #region IEspionageReport Members

            IPosition IEspionageReport.Position
            {
                get { return this.Position; }
              
            }

            IPlayerFull IEspionageReport.Player
            {
                get { return this.Player; }
            }

            IEspionage IEspionageReport.Espionage
            {
                get { return this.Espionage; }
            }

            IEnumerable<IReportShip> IEspionageReport.ReportShips
            {
                get { return this.ReportShips; }
            }

            #endregion
        }

    public partial class Alliance : IAlliance
    {



    }

    public partial class Permission : IPermission { }

    public partial class Player : IPlayerFull
    {
        #region IPlayer Members

        IAlliance IPlayerFull.Alliance
        {
            get
            {
                return this.Alliance;
            }
        }

        #endregion


        #region IPlayer Members

        int IPlayer.PlayerId
        {
            get { return this.Id; }
        }


        #endregion
    }

    public partial class aspnet_Membership : IMembership { }

    public partial class PlayerHistory : IPlayerFull
    {
        #region IPlayerFull Members

        IAlliance IPlayerFull.Alliance
        {
            get { return this.Alliance; }
        }

        #endregion

        DateTime IPlayer.Updated
        {
            get { return this.Date; }
        }


    }

    public partial class Universe : IUniverse { }
    public partial class ReportShip : IReportShip
    {
        #region IReportShip Members

        ICombatUnit IReportShip.CombatUnit
        {
            get { return this.CombatUnit; }
        }

        #endregion
    }
    public partial class CombatUnit : ICombatUnit
    {
    }
}
